/***
 * 
 * 
 * 
 */

//可迭代对象
let arr = ['foo', 'bar'];
//迭代器工厂函数
console.log(arr[Symbol.iterator]);//[Function: values]
//迭代器对象
let iter = arr[Symbol.iterator]();
console.log(iter);//Object [Array Iterator] {}
//执行迭代
console.log(iter.next());//{value: 'foo', done: false}
console.log(iter.next());//{ value: 'bar', done: false }
console.log(iter.next());//{ value: undefined, done: true }

//可迭代对象的实例之间没有联系
let arr2 = ['foo', 'bar'];
let iter1 = arr[Symbol.iterator]();
let iter2 = arr[Symbol.iterator]();
console.log(iter1.next());
console.log(iter2.next());
console.log(iter2.next());
console.log(iter1.next());
//{ value: 'foo', done: false }
//{ value: 'foo', done: false }
//{ value: 'bar', done: false }
//{ value: 'bar', done: false }


//用游标来遍历，可迭代对象被修改，跟着修改
let arr3 = ['foo', 'bar'];
let iter3 = arr[Symbol.iterator]();
console.log(iter3.next());//{value: 'foo', done: false}
arr3.splice(1,0,'baz');
console.log(iter3.next());//{value: 'bar', done: false}


//实现一个有迭代器接口的类
class Foo {
    [Symbol.iterator]() {
        return {
            next: function () {
                return { value: 'foo..', done: true };
            }
        };
    }
}

let foo = new Foo();
let iter4 = foo[Symbol.iterator]();
console.log(iter4.next().value);//foo..







// function createIterator(items) {
//     let i = 0;
//     return {
//         next: function () {
//             let done = (i >= items.length);
//             let value = !done ? items[i++] : undefined;
//             return {
//                 done,
//                 value
//             }
//         }
//     };
// }
// //调用迭代器工厂函数
// let iterator = createIterator(arr);
// console.log(iterator.next()); //{done: false, value: 'foo'}
// console.log(iterator.next()); //{done: false, value: 'bar'}
// console.log(iterator.next()); //{done: true, value: undefined}


